package cn.touna.jss.modules.callback.controller;


import cn.touna.jss.common.cache.HbaseComponent;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.jss.common.util.HttpParseUtil;
import cn.touna.jss.modules.callback.entity.DianHuaBangCallback;
import cn.touna.jss.modules.third.dianhuabang.service.IDianHuaBangService;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.ServiceContext;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

/**
 * 电话帮回调
 */
@RestController
public class DianHuaBangCallbackController {

    private static final Logger LOG = LogManager.getLogger(DianHuaBangCallbackController.class);

    @Autowired
    private IDianHuaBangService dianHuaBangService;

    @Autowired
    private KafkaComponent kafkaComponent;

    @Autowired
    private HbaseComponent hbaseComponent;

    /**
     * 催收接口回调
     *
     * @param body:三方回调推送数据
     * @return
     */
    @RequestMapping("/callback/dianhuabang/cuishou")
    public JSONObject cuishou(@RequestBody String body, HttpServletRequest request) {
        JSONObject result = new JSONObject();
        try {
            Map<String, String> headParams = HttpParseUtil.getHeadersInfo(request);
            LOG.info("【电话帮】回调请求头:{}", headParams);
            if (StringUtils.isEmpty(body)) {
                LOG.warn("请求参数为空");
                result.put("status", "400");
                result.put("msg", "request param is empty");
                return result;
            }
            LOG.info("【电话帮】回调原始报文body:{}", body);
            String json = URLDecoder.decode(body, "UTF-8");
            //1. 解析推送结果
            JSONObject responseJsonObject = JSONObject.parseObject(json);
            String sid = responseJsonObject.getString("sid");
            DianHuaBangCallback requestHistory = dianHuaBangService.getDianHuaBangCallbackBySid(sid);
            if (requestHistory == null) {
                LOG.warn("未查询到sid:{}的调用历史", sid);
                result.put("status", "400");
                result.put("msg", "未查询到sid:" + sid + "的调用历史");
                return result;
            }

            //2. 生成请求
            CreditQueryRequest creditQueryRequest = new CreditQueryRequest();
            creditQueryRequest.setCrNo(ServiceContext.genUniqueId());
            creditQueryRequest.setBizType(request.getParameter("BizType"));
            creditQueryRequest.setMobile(requestHistory.getMobile());
            creditQueryRequest.setIdCard(requestHistory.getIdCard());
            creditQueryRequest.setMethod("dianhuabang.cuishou");
            creditQueryRequest.setServiceName("dianhuabang");
            creditQueryRequest.setMethodName("cuishou");
            creditQueryRequest.setQueryTime(requestHistory.getDateCreated());
            creditQueryRequest.setParams(JSONObject.parseObject(requestHistory.getRequestParams()));

            //3. 生成响应
            responseJsonObject.put("success", "true");
            responseJsonObject.put("note", "查询电话帮催收结果成功");
            Response response = new Response().success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, responseJsonObject);

            //4. 推送给变量系统，存储到hbase
            kafkaComponent.sendSyncCallData(creditQueryRequest, response);
            hbaseComponent.saveCacheData(creditQueryRequest, response);
            LOG.info("PRO 调用【电话帮催收回调】发送kafka写入hbase,request:{},response:{}", JSONObject.toJSON(creditQueryRequest), JSONObject.toJSON(response));

            //5. 更新查询请求
            requestHistory.setStatus((byte) 2);
            requestHistory.setDateUpdated(new Date());
            int success = dianHuaBangService.updateRequestHistory(requestHistory);

            //三方规定如果成功必须返回OK
            result.put("status", "0");
            result.put("msg", success > 0 ? "OK" : "Fail");
            return result;
        } catch (Exception e) {
            LOG.error("PRO 调用【电话帮催收回调】异常, e:{}", e);
            result.put("status", "400");
            result.put("msg", "error");
            return result;
        }
    }
}
